Skip to main content

Java Basics

1. Sample Code in Java

a. What is main

The main method is the entry point of a Java application.

  • Syntax:

    public static void main(String[] args) {
    // Code to be executed
    }
  • Key Points:

    • public: Accessible from anywhere.
    • static: Belongs to the class, not an instance.
    • void: Returns nothing.
    • String[] args: Command-line arguments.

b. What is static

  • Definition: A keyword to denote a method or variable that belongs to the class rather than an instance.

  • Example:

    class Example {
    static int count = 0; // Static variable

    static void displayCount() { // Static method
    System.out.println("Count: " + count);
    }
    }

2. Comments

a. Single Line

  • Syntax: // This is a single-line comment
  • Example:
    // This is a comment
    int x = 10; // Variable declaration

b. Multi-Line

  • Syntax:
    /* This is a
    multi-line comment */
  • Example:
    /*
    This code demonstrates
    multi-line comments.
    */
    int y = 20;

3. Data Types

a. byte

  • 1 byte (8 bits), range: -128 to 127.
  • Example:
    byte b = 100;

b. short

  • 2 bytes (16 bits), range: -32,768 to 32,767.
  • Example:
    short s = 32000;

c. int

  • 4 bytes (32 bits), range: -2^31 to 2^31-1.
  • Example:
    int i = 123456;

d. float

  • 4 bytes (32 bits), precision: 6-7 decimal digits.
  • Example:
    float f = 3.14f;

e. double

  • 8 bytes (64 bits), precision: 15-16 decimal digits.
  • Example:
    double d = 3.14159;

f. char

  • 2 bytes (16 bits), stores a single Unicode character.
  • Example:
    char c = 'A';

4. Operators

a. Arithmetic

int sum = 5 + 3; // Addition
int diff = 5 - 3; // Subtraction
int prod = 5 * 3; // Multiplication
int quo = 5 / 3; // Division
int rem = 5 % 3; // Modulus

b. Unary

int x = 5;
System.out.println(++x); // Pre-increment
System.out.println(x--); // Post-decrement

c. Relational

int a = 10, b = 20;
System.out.println(a > b); // false

d. Logical

boolean res = (a > b) && (b > 0); // AND

e. Assignment

int num = 5;
num += 10; // Equivalent to num = num + 10

f. Bitwise

int result = 5 & 3; // Bitwise AND

g. Ternary

String result = (a > b) ? "Greater" : "Smaller";

5. String

a. Strings and Immutability

  • Strings in Java:

    • A String is a sequence of characters.
    • Strings in Java are objects of the String class.
    • They are defined using double quotes:
      String str = "Hello";
  • Immutability:

    • Strings are immutable, meaning their content cannot be changed once created.
    • Any operation that appears to modify a string (e.g., concatenation) creates a new String object instead of modifying the existing one.
  • Example:

    String s1 = "Hello";
    String s2 = s1.concat(" World");
    System.out.println(s1); // Output: Hello
    System.out.println(s2); // Output: Hello World

b. Char Array to String

  • Strings can be constructed from character arrays.
  • Example:
    char[] chars = {'J', 'a', 'v', 'a'};
    String str = new String(chars);
    System.out.println(str); // Output: Java

c. String Methods

1. Concatenate:

  • Combines two strings.
  • Example:
    String first = "Hello";
    String second = "World";
    String result = first + " " + second; // Using `+` operator
    System.out.println(result); // Output: Hello World

2. Length:

  • Returns the number of characters in a string.
  • Example:
    String str = "Java";
    System.out.println(str.length()); // Output: 4

3. charAt:

  • Returns the character at a specified index.
  • Example:
    String str = "Java";
    System.out.println(str.charAt(2)); // Output: v

4. Substring:

  • Extracts a part of the string.
  • Example:
    String str = "Programming";
    System.out.println(str.substring(3, 8)); // Output: gramm

5. Equals:

  • Compares two strings for equality.
  • Example:
    String str1 = "Java";
    String str2 = "java";
    System.out.println(str1.equals(str2)); // Output: false
    System.out.println(str1.equalsIgnoreCase(str2)); // Output: true

6. Input/Output

a. Scanner Class - Implementation

  • The Scanner class in java.util is used to take input from the user.

  • Key Methods:

    • nextInt(): Reads an integer.
    • nextDouble(): Reads a double.
    • nextLine(): Reads a full line (including spaces).
    • nextBoolean(): Reads a boolean.
    • next(): Reads a single word (until a space is encountered).
  • Example Implementation:

    import java.util.Scanner;

    public class InputExample {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter an integer: ");
    int num = scanner.nextInt();

    System.out.print("Enter a double: ");
    double decimal = scanner.nextDouble();

    scanner.nextLine(); // Consume the leftover newline

    System.out.print("Enter a string: ");
    String text = scanner.nextLine();

    System.out.println("Integer: " + num);
    System.out.println("Double: " + decimal);
    System.out.println("String: " + text);

    scanner.close();
    }
    }

b. Common Scanner Methods

1. nextInt():

  • Reads an integer value.
  • Example:
    int number = scanner.nextInt();

2. nextDouble():

  • Reads a double value.
  • Example:
    double price = scanner.nextDouble();

3. nextLine():

  • Reads the entire line (including spaces).
  • Example:
    String sentence = scanner.nextLine();

4. nextBoolean():

  • Reads a boolean value (true or false).
  • Example:
    boolean isActive = scanner.nextBoolean();

5. next():

  • Reads a single word until a space or newline is encountered.
  • Example:
    String word = scanner.next();

c. BufferedReader

  • Used for faster input than the Scanner class.

  • Requires handling exceptions.

  • Example:

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;

    public class BufferedReaderExample {
    public static void main(String[] args) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
    System.out.print("Enter a string: ");
    String input = reader.readLine();

    System.out.println("You entered: " + input);
    } catch (IOException e) {
    System.out.println("An error occurred: " + e.getMessage());
    }
    }
    }

7. Type Casting

a. Implicit

int x = 10;
double y = x; // Automatic conversion

b. Explicit

double d = 10.5;
int i = (int) d; // Manual conversion

8. Constants

a. final Keyword

final int MAX = 100;

9. Arrays

a. Declaration and Access

int[] arr = {1, 2, 3};
System.out.println(arr[0]); // Access

b. For Each Loop

for (int num : arr) {
System.out.println(num);
}

c. 2D Array

int[][] matrix = {{1, 2}, {3, 4}};

10. Conditional Statements

a. If-Else

if (x > 0) {
System.out.println("Positive");
} else {
System.out.println("Negative");
}

b. Switch

switch (day) {
case 1: System.out.println("Monday"); break;
default: System.out.println("Invalid");
}

11. Loops

a. For Loop

for (int i = 0; i < 5; i++) {
System.out.println(i);
}

b. While Loop

int i = 0;
while (i < 5) {
System.out.println(i++);
}

12. Exception Handling

Try-Catch

try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}